package com.dq.edusms.service.impl;

import com.dq.edusms.service.SmsService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @project: guli_parent
 * @ClassName: SmsServiceImpl
 * @author: dq
 * @creat: 2022/8/7 15:35
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    //你创建的应用AppID
    public static final String appid = "1400718098";
    //你的正文模板ID
    public static final String templated = "1501782";
    //你的签名模板中的内容,不是签名ID
    public static final String smsSign = "编程学习笔记";
    //key  secret
    public static final String secretId = "AKIDHX0Pl8bzDPTN6dx74mGVWLyzlJjyGTch";
    public static final String secretKey = "Us78wlXAYjpmX4QDqFZrP4jLrJXiFikl";

    @Override
    public boolean send(HashMap<String, Object> param, String phoneNum) {
        if (StringUtils.isEmpty(phoneNum)){
            return false;
        }
        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey，见《创建secretId和secretKey》小节
        Credential cred = new Credential(secretId, secretKey);

        // 实例化要请求产品(以cvm为例)的client对象
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod(ClientProfile.SIGN_TC3_256);
        //第二个ap-chongqing 填产品所在的区 sms.ap-chengdu.tencentcloudapi.com
        SmsClient smsClient = new SmsClient(cred, "ap-chengdu");
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        //appId ,见《创建应用》小节
        sendSmsRequest.setSmsSdkAppid(appid);
        //发送短信的目标手机号，可填多个。
        String[] phones={"+86"+phoneNum};
        sendSmsRequest.setPhoneNumberSet(phones);
        //模版id,见《创建短信签名和模版》小节
        sendSmsRequest.setTemplateID(templated);
        //模版参数，从前往后对应的是模版的{1}、{2}等,见《创建短信签名和模版》小节
        String code = (String) param.get("code");
        String [] templateParam={code};
        sendSmsRequest.setTemplateParamSet(templateParam);
        //签名内容，不是填签名id,见《创建短信签名和模版》小节
        sendSmsRequest.setSign(smsSign);
        try {
            //发送短信
            SendSmsResponse sendSmsResponse= smsClient.SendSms(sendSmsRequest);
            log.info("into");
            System.out.println(sendSmsResponse.getSendStatusSet()[0].getCode());
            System.out.println(sendSmsResponse.getSendStatusSet()[0]);
            if (sendSmsResponse.getSendStatusSet()[0].getCode().contains("Ok")){
                return true;
            }else {
                return false;
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }
}
